// 认证管理工具类
class AuthManager {
    constructor() {
        this.sessionKey = 'session_id';
        this.userInfoKey = 'user_info';
        this.expiresKey = 'session_expires';
    }

    // 获取Cookie值
    getCookie(name) {
        const value = "; " + document.cookie;
        const parts = value.split("; " + name + "=");
        if (parts.length === 2) return parts.pop().split(";").shift();
        return null;
    }

    // 设置Cookie
    setCookie(name, value, days = 1) {
        const expires = new Date();
        expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
        document.cookie = name + "=" + value + ";expires=" + expires.toUTCString() + ";path=/";
    }

    // 删除Cookie
    deleteCookie(name) {
        document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
    }

    // 获取本地存储的值
    getLocalStorage(key) {
        try {
            const value = localStorage.getItem(key);
            return value ? JSON.parse(value) : null;
        } catch (e) {
            return null;
        }
    }

    // 设置本地存储
    setLocalStorage(key, value) {
        try {
            localStorage.setItem(key, JSON.stringify(value));
        } catch (e) {
            console.error('无法设置localStorage:', e);
        }
    }

    // 删除本地存储
    removeLocalStorage(key) {
        try {
            localStorage.removeItem(key);
        } catch (e) {
            console.error('无法删除localStorage:', e);
        }
    }

    // 保存登录信息
    saveAuth(sessionId, userInfo, expiresAt) {
        // 保存到Cookie（用于HTTP请求）
        this.setCookie(this.sessionKey, sessionId, 1);
        
        // 保存到localStorage（用于页面间数据共享）
        this.setLocalStorage(this.sessionKey, sessionId);
        this.setLocalStorage(this.userInfoKey, userInfo);
        this.setLocalStorage(this.expiresKey, expiresAt);
        
        console.log('登录信息已保存:', userInfo);
    }

    // 获取Session ID
    getSessionId() {
        // 优先从Cookie获取
        const cookieSession = this.getCookie(this.sessionKey);
        if (cookieSession) return cookieSession;
        
        // 备用：从localStorage获取
        return this.getLocalStorage(this.sessionKey);
    }

    // 获取用户信息
    getUserInfo() {
        return this.getLocalStorage(this.userInfoKey);
    }

    // 获取过期时间
    getExpiresAt() {
        return this.getLocalStorage(this.expiresKey);
    }

    // 检查是否已登录
    isLoggedIn() {
        const sessionId = this.getSessionId();
        const userInfo = this.getUserInfo();
        const expiresAt = this.getExpiresAt();
        
        if (!sessionId || !userInfo || !expiresAt) {
            return false;
        }

        // 检查是否过期
        const now = new Date();
        const expires = new Date(expiresAt);
        if (now >= expires) {
            this.logout();
            return false;
        }

        return true;
    }

    // 验证Session（向服务器验证）
    async validateSession() {
        const sessionId = this.getSessionId();
        if (!sessionId) {
            return false;
        }

        try {
            const response = await fetch('/user/session/refresh', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + sessionId,
                    'Content-Type': 'application/json'
                }
            });

            if (response.ok) {
                const data = await response.json();
                if (data.result) {
                    // 更新过期时间
                    this.setLocalStorage(this.expiresKey, data.expires_at);
                    return true;
                }
            }
        } catch (error) {
            console.error('Session验证失败:', error);
        }

        this.logout();
        return false;
    }

    // 登出
    logout() {
        // 清除Cookie
        this.deleteCookie(this.sessionKey);
        
        // 清除localStorage
        this.removeLocalStorage(this.sessionKey);
        this.removeLocalStorage(this.userInfoKey);
        this.removeLocalStorage(this.expiresKey);
        
        console.log('用户已登出');
    }

    // 获取Authorization头
    getAuthHeaders() {
        const sessionId = this.getSessionId();
        if (sessionId) {
            return {
                'Authorization': 'Bearer ' + sessionId
            };
        }
        return {};
    }

    // 处理需要登录的AJAX请求
    authenticatedRequest(options) {
        if (!this.isLoggedIn()) {
            alert('请先登录！');
            window.location.href = 'login.html';
            return;
        }

        // 添加认证头
        options.headers = Object.assign({}, options.headers, this.getAuthHeaders());
        
        // 添加错误处理
        const originalError = options.error;
        options.error = (xhr, status, error) => {
            if (xhr.status === 401) {
                alert('登录已过期，请重新登录！');
                this.logout();
                window.location.href = 'login.html';
                return;
            }
            if (originalError) {
                originalError(xhr, status, error);
            }
        };

        return $.ajax(options);
    }

    // 显示用户信息在页面上
    displayUserInfo(container) {
        const userInfo = this.getUserInfo();
        if (userInfo && container) {
            const userDisplay = `
                <div class="user-info">
                    <span class="user-name">欢迎, ${userInfo.username}</span>
                    <button class="logout-btn" onclick="authManager.logout(); window.location.reload();">登出</button>
                </div>
            `;
            $(container).html(userDisplay);
        }
    }

    // 初始化页面认证状态
    initPage() {
        if (this.isLoggedIn()) {
            // 如果已登录，验证session有效性
            this.validateSession();
            return true;
        }
        return false;
    }
}

// 创建全局实例
const authManager = new AuthManager(); 